﻿using Furion;
using Furion.DatabaseAccessor;
using Microsoft.Extensions.DependencyInjection;
using Queer.Data.DbContexts;
using SqlSugar;
using System;

namespace Queer.Data
{
    [AppStartup(10)]
    public class DataAppStartup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            string dbType = App.Configuration["ConnectionStrings:DBType"];

            // 数据库访问注册
            services.AddDatabaseAccessor(options =>
            {
                // 注册数据库访问上下文
                switch (dbType.ToLower())
                {
                    case "sqlserver":
                        options.AddDbPool<DefaultDbContext>(DbProvider.SqlServer);
                        break;
                    case "mysql":
                        options.AddDbPool<DefaultDbContext>(DbProvider.MySqlOfficial);
                        break;
                    default:
                        throw new Exception("未找到数据库配置");
                }
            });

            // 注册 SqlSugar 服务
            services.AddSqlSugar(new ConnectionConfig
            {
                ConnectionString = App.Configuration["ConnectionStrings:DefaultConnectionString"],
                DbType = ReturnSqlSugarDbType(dbType),
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            });
        }

        private DbType ReturnSqlSugarDbType(string dbType)
        {
            switch (dbType.ToLower())
            {
                case "sqlserver":
                    return DbType.SqlServer;
                case "mysql":
                    return DbType.MySql;
                default:
                    throw new Exception("未找到数据库配置");
            }
        }
    }
}